package com.dsz.util;

import Dao.DatabaseConnection;
import Dao.WeatherInfoGet;
import POJO.Weather;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class WeatherApp {
    public static void main(String[] args) throws IOException {
        //查询weatherinfo数据库，并把数据插入到table中
        WeatherInfoGet.main(args);
      //查询weatherinfo数据库,将值返回给weatherLsit
        List<Weather> weatherList = new ArrayList<>();
        try (
                Connection connection = DatabaseConnection.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM weather_info");
                ResultSet resultSet = preparedStatement.executeQuery()
        ) {
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String weatherData = resultSet.getString("weather_data");
                weatherList.add(new Weather(id, weatherData));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 打印天气列表
        for (Weather weather : weatherList) {
            System.out.println("ID: " + weather.getId() + ", Weather Data: " + weather.getWeatherData());
        }


        // 创建JFrame
        JFrame frame = new JFrame("Weather List");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLayout(new BorderLayout());

        // 创建JPanel来组织布局
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        // 创建JTable并设置模型
        String[] columnNames = {"ID", "Weather Data"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        for (Weather weather : weatherList) {
            tableModel.addRow(new Object[]{weather.getId(), weather.getWeatherData()});
        }

        JTable table = new JTable(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(350, 200));
        table.setFillsViewportHeight(true);

        // 创建JScrollPane来包含JTable
        JScrollPane scrollPane = new JScrollPane(table);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 将JPanel添加到JFrame中
        frame.add(panel, BorderLayout.CENTER);

        // 设置窗口可见
        frame.setVisible(true);
    }
}
